// 设备控制映射表
const deviceControlMap = {
    "light_bedroom": { type: "1", key: 304 },
    "light_livingroom": { type: "1", key: 305 },
    "air_purifier": { type: "1", key: 306 },
    "air_switch": { type: "2", key: 101 },
    "humidifier": { type: "2", key: 103 },
    "curtain": { type: "2", key: 104 },
    "robot_vacuum": { type: "2", key: 105 },
    "washing_machine": { type: "2", key: 106 }
};

// 发送控制命令
function sendDeviceCommand(deviceId, elementId) {
    const device = deviceControlMap[deviceId];
    const action = elementId.includes('_on') ? '1' : '0';
    const cmd = `${device.type}+${device.key}+${action}`;

    console.log("发送控制命令:", cmd);

    fetch("http://192.168.51.65:8080/control", {
        method: 'POST',
        headers: { 'Content-Type': 'text/plain' },
        body: cmd
    })
        .then(response => response.text())
        .then(data => {
            console.log("控制响应:", data);
            updateButtonState(deviceId, action === '1');
        })
        .catch(error => {
            console.error("控制失败:", error);
        });
}

// 更新按钮状态
function updateButtonState(deviceId, isOn) {
    const onBtn = document.getElementById(`${deviceId}_on`);
    const offBtn = document.getElementById(`${deviceId}_off`);

    if (onBtn && offBtn) {
        onBtn.classList.toggle('active', isOn);
        offBtn.classList.toggle('active', !isOn);
        onBtn.checked = isOn;
        offBtn.checked = !isOn;
    }
}

// 刷新传感器数据
function refreshSensorData() {
    fetch('http://192.168.51.65:8080/get')  // 改为完整URL
        .then(res => res.json())
        .then(data => {
            document.getElementById('temp').textContent =
                data.temperature.toFixed(1) + '°C';
            document.getElementById('humi').textContent =
                data.humidity.toFixed(1) + '%';
        })
        .catch(error => console.error('获取温湿度失败:', error));
}

// 页面初始化
window.onload = function () {
    // 每5秒刷新传感器数据
    refreshSensorData();
    setInterval(refreshSensorData, 5000);

    // 初始化设备状态
    fetch('/device_status')
        .then(response => response.json())
        .then(data => {
            Object.keys(data.devices).forEach(deviceId => {
                updateButtonState(deviceId, data.devices[deviceId].isOn);
            });
        });
};

// 统一控制处理
function controlDevice(element) {
    const deviceId = element.name;
    const action = element.id.includes('_on') ? '1' : '0';
    const device = deviceControlMap[deviceId];

    // 格式改为 key+action（如 "304+1"）
    const cmd = `${device.key}+${action}`;

    fetch('http://192.168.51.65:8080/control', {
        method: 'POST',
        headers: { 'Content-Type': 'text/plain' },
        body: cmd
    })
}
setInterval(refreshSensorData, 5000);